#!/bin/bash
set -e

namespace=""
K8S_JVM_POD=""
FORWARD_PORT=31757

while [[ $# -gt 0 ]]; do
  case $1 in
  -n|--namespace)
    shift
    namespace="$1"
    ;;
  -p)
    shift
    FORWARD_PORT="$1"
    ;;
  esac
  shift
done

if [[ -z ${namespace} ]]; then
    echo "Please give the namespace parameter via -n"
    exit
fi

kubectl_context="kubectl -n $namespace"

function select_pod_if_needs() {
  echo "Here are all available pods"
    echo "----------------------------- PODs ----------------------------------"
    local pods=`${kubectl_context} get pods --no-headers -o custom-columns=":metadata.name" | awk ' {print NR". " $0}'`
    echo "$pods"
    local line_number
    line_number=$(echo "$pods" | awk 'END{print NR}')
  while :; do
    # shellcheck disable=SC2162
    read -p "please pick one:" input_number

     if (("$input_number" >= 1 && "$input_number" <= ${line_number})); then
      input_pod_name=$(echo "$pods" | awk -v col=2 ' /^'"$input_number"\.'/ {print $col}')
      if [[ -z "$input_pod_name" ]]; then
        echo "Pod select error"
        exit 1
      fi
      input_pod_name="$input_pod_name"
      break
    else
      echo "Not recognized input $input_pod_name"
    fi
  done
  K8S_JVM_POD="$input_pod_name"
}

if [[ -z ${K8S_JVM_POD} ]]; then
    echo "POD has not provide by parameter."
    select_pod_if_needs
fi

EXEC="${kubectl_context} exec ${K8S_JVM_POD}"
CP="${kubectl_context} cp ${K8S_JVM_POD}"

function select_pid_if_needs() {
  while :; do
    echo "PID does not given, here are the JVM processes"
    echo "----------------------------- PIDs ----------------------------------"
    ${EXEC} -- jps 2>/dev/null
    # shellcheck disable=SC2162
    read -p "please pick one:" input_pid

    if [[ -n "$input_pid" ]]; then
      break
    else
      echo "Not recognized input"
    fi
  done
  K8S_JVM_PID="$input_pid"
}

if [[ -z ${K8S_JVM_PID} ]]; then
  select_pid_if_needs
fi


JPROFILER_PACKAGE=jprofiler_linux_11_1_4.tar.gz
JPROFILER_PACKAGE_URL=https://download-gcdn.ej-technologies.com/jprofiler/${JPROFILER_PACKAGE}

if [[ ! -f ${JPROFILER_PACKAGE} ]]; then
    wget -O "${JPROFILER_PACKAGE}" "${JPROFILER_PACKAGE_URL}"
fi

if ! ${EXEC} -- find /leandev/${JPROFILER_PACKAGE} &>/dev/null; then
    echo "${JPROFILER_PACKAGE} not found on the server, copying..."
    ${kubectl_context} cp "${JPROFILER_PACKAGE}" "${K8S_JVM_POD}:/leandev/${JPROFILER_PACKAGE}"
else
    echo "${JPROFILER_PACKAGE}  already found in the server"
fi

${EXEC} -- tar -C /leandev -xf "/leandev/${JPROFILER_PACKAGE}"

JPROFILER_PORT=31757

${EXEC} -- /leandev/jprofiler11.1.4/bin/jpenable --pid="${K8S_JVM_PID}" --port=${JPROFILER_PORT} --noinput --gui
${kubectl_context} port-forward ${K8S_JVM_POD} "${FORWARD_PORT}":${JPROFILER_PORT}